package sample

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"my-gameserver-go/logic/global"
	"my-gameserver-go/logic/sample/jsonconf"
	"reflect"
	"strconv"
)

type Manager struct {
}

var InsSampleManager *Manager

var ConfigSampleMap = make(map[string]map[int32]any)
var ConfigSampleAry = make(map[string]any)

func init() {
	InsSampleManager = &Manager{}
	//注册所有的对象
	c1 := &jsonconf_SlgStarCamp.SlgStarCamp{}
	ConfigSampleAry[global.SimpleName(c1)] = c1

}

func (m Manager) Start() {

	// 读取当前目录中的所有文件和子目录
	jsonfiles, err := ioutil.ReadDir(`./config/sample`)
	if err != nil {
		panic(err)
	}
	// 获取文件，并输出它们的名字
	for _, file := range jsonfiles {
		fname := "./config/sample/" + file.Name()
		bytes, err := ioutil.ReadFile(fname)
		sampleName := global.HeadName(file.Name())
		if err != nil {
			panic(err)
		}
		if ConfigSampleAry[sampleName] != nil {
			val := ConfigSampleAry[sampleName]
			temp := make([]any, 30)
			err := json.Unmarshal(bytes, &temp)
			if err != nil {
				fmt.Println(err.Error())
			}
			temp2 := make(map[int32]any)
			for _, single := range temp {
				sMap := single.(map[string]any)
				for key, v := range sMap {
					filed := reflect.ValueOf(val).Elem().FieldByName(key)
					keyKind := filed.Kind()
					strV := v.(string)
					if keyKind == reflect.Int32 {
						elementV, _ := strconv.Atoi(strV)
						filed.SetInt(int64(elementV))
						if key == "Sid" {
							temp2[int32(elementV)] = val
						}
					} else if keyKind == reflect.String {
						filed.SetString(strV)
					} else if keyKind == reflect.Bool {
						if v == nil || v == "" {
							filed.SetBool(false)
						} else {
							elementV, _ := strconv.ParseBool(strV)
							filed.SetBool(elementV)
						}
					}

				}
				ConfigSampleMap[sampleName] = temp2
			}
		}
	}
}
func GetSample(sampleName string, sid int32) any {
	temp := ConfigSampleMap[sampleName]
	if temp == nil {
		return nil
	}
	return temp[sid]
}
